import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterapp2/model/count_model.dart';
import 'package:provider/provider.dart';

class TestProvider extends StatelessWidget {
  CountModel countModel;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<CountModel>(
      create: (context) {
//        countModel.addListener(() {
////          var count = countModel.count;
//          Fluttertoast.showToast(msg: '111');
//        });
        return countModel ?? CountModel();
      },
      child: Scaffold(
        appBar: AppBar(
          title: Consumer<CountModel>(
            builder: (context, value, child) => Text("${value.count}"),
          ),
        ),
        body: testChangeNotifierProvider(),
      ),
    );
  }

  ///与最基础的Provider小部件不同，ChangeNotifierProvider会监听其提供出去的模型对象中的更改。
  ///当有值更改后，它将重建下方所有的Consumer和使用Provider.of<MyModel>(context)监听并获取提供值的地方。
  testChangeNotifierProvider() {
    return Column(
      children: <Widget>[
        Builder(builder: (context) {
          return Text("随机数：${Random().nextInt(10)}");
        }),
        Builder(
          builder: (context) {
            // 两种获取方式 Provider.of,listen控制是否监听变化
            var model = Provider.of<CountModel>(context, listen: false);
            return Container(
              height: 100,
              margin: const EdgeInsets.only(top: 20),
              width: MediaQuery.of(context).size.width,
              padding: const EdgeInsets.all(20),
              alignment: Alignment.center,
              color: Colors.lightBlueAccent,
              child: Text('当前是：${model.count}'),
            );
          },
        ),
        Consumer<CountModel>(
          // 两种获取方式 Consumer
          builder: (context, data, child) {
            return Container(
              margin: const EdgeInsets.only(top: 20),
              width: MediaQuery.of(context).size.width,
              padding: const EdgeInsets.all(20),
              alignment: Alignment.center,
              color: Colors.lightBlueAccent,
              child: Text('当前是：${data.count}'),
            );
          },
        ),
        Consumer<CountModel>(
          builder: (context, data, child) {
            return FlatButton(
              color: Colors.tealAccent,
              onPressed: () {
                data.incrementCounter();
                // 通知所有观察者刷新
                data.notifyListeners();
              },
              child: Icon(Icons.add),
            );
          },
        ),
      ],
    );
  }
}
